package com.glodon.paas.qto.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.glodon.paas.job.model.TaskStatus;
import com.glodon.paas.qto.dao.TaskRepository;
import com.glodon.paas.qto.model.Task;
import com.glodon.paas.qto.model.TaskProgress;
import com.glodon.paas.qto.service.DispatcherService;
import com.glodon.paas.qto.service.QtoService;
import com.glodon.paas.qto.service.TaskService;

@Service
public class TaskServiceImpl implements TaskService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    // 时间间隔:默认1分钟,单位：毫秒
    @Value("${taskCheckInterval:300000}")
    private int interval;

    // 时间跨度:24小时，单位：小时
    @Value("${taskCheckSpan:12}")
    private int span;

    @Autowired
    private DispatcherService dispatcherService;
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private QtoService qtoService;

    @Override
    @Scheduled(fixedRate = 300000)
    public void checkUnCompleteTask() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MILLISECOND, -1 * interval);
        Date toTime = calendar.getTime();
        calendar.add(Calendar.HOUR_OF_DAY, -1 * span);
        Date fromTime = calendar.getTime();
        Pageable page = new PageRequest(0, 100);
        List<Task> localTasks = taskRepository.findUncomleteTasks(fromTime, toTime, page);
        logger.debug("find {} uncompleted task(s)", localTasks.size());
        for (Task localTask : localTasks) {
            TaskProgress jobServerTaskProgress = dispatcherService.queryTaskProgress(localTask.getJobServerTaskId());
            if (jobServerTaskProgress != null) {
                qtoService.processTaskNotify(localTask.getJobServerTaskId(), jobServerTaskProgress);
            } else {// 失败，置task为失败
                localTask.setStatus(TaskStatus.failure);
                taskRepository.save(localTask);
            }
        }
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public void setSpan(int span) {
        this.span = span;
    }

    public void setDispatcherService(DispatcherService dispatcherService) {
        this.dispatcherService = dispatcherService;
    }

    public void setTaskRepository(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }

    public void setQtoService(QtoService qtoService) {
        this.qtoService = qtoService;
    }
}
